﻿using BaseAuthRole.Domain.Input;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using RS.Environment;
using RS.Tool.Init;
using System.Web;

namespace BaseAuthRole.Web.Filters
{
    public class AuthCheckFilter: ActionFilterAttribute
    { //action执行后
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            
        }
        //action执行前
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var return_url ="http"+$"{(context.HttpContext.Request.IsHttps?"s":"")}"+"://" +context.HttpContext.Request.Host + context.HttpContext.Request.Path + context.HttpContext.Request.QueryString;

            var para = (PublicAppAuthorizeIput)context.ActionArguments.First().Value;

            var method = context.HttpContext.Request.Method;

            //通过cookie检查有效性 uid 及token 有效性

            var userloginInfo = UserCookieHelper.GetCookieUserInfo();
            //未登录检查第三方认证
            if (userloginInfo == null)
            {

                //检查第三方认证
                var TDAuthable = ConfigurationHelper.GetAppSettings("TDAuthable");
                //未启用
                if (TDAuthable != "1")
                {
                    var url = $"{RS.Environment.ConfigurationHelper.GetAppSettings("VirtualUrl")}/Home/Login?return_url={HttpUtility.UrlEncode(return_url)}";

                    context.Result = new RedirectResult(url);
                }
                //已启用
                else { 
                   
                    var AppId = para.AppId;
                    var Scope = para.Scope;
                    var RedirectUrl = para.RedirectUri;

                    var code_url = $"{ConfigurationHelper.GetAppSettings("TDCodeUrl")}?AppId={AppId}&Scope={Scope}&return_url={HttpUtility.UrlEncode(RedirectUrl)}";

                    var authorize_url = ConfigurationHelper.GetAppSettings("TDAuthorizeUrl")+HttpUtility.UrlEncode(code_url);

                    context.Result = new RedirectResult(authorize_url);
                }
            }
            //直接认证
            else { 
            
            
            }

        }

    }
}
